package top.ed333.mcplugins.configurableevents.handler;

import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
import top.ed333.mcplugins.configurableevents.ConfigManager;
import top.ed333.mcplugins.configurableevents.ConsoleSender;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PkgManager {
    private static final Pattern placeholderPkgRef = Pattern.compile("@[0-9a-zA-z]+");
    private static final String placeholderKeyRef = "$key";

    private static final Map<String, String> packages = new HashMap<>();

    public static String packageFromName(@NotNull String name) {
        String result;
        if (name.startsWith("@")) {
            name = name.substring(1);
        }
        result = packages.get(name);
        return result;
    }

    public static void initPackages() {
        ConfigurationSection pkgConfigurationSec = ConfigManager.getDefaultConfig().getConfigurationSection("event_packages");
        pkgConfigurationSec.getKeys(false).forEach(key -> {
            String pkg = pkgConfigurationSec.getString(key);
            Matcher matcher = placeholderPkgRef.matcher(pkg);

            while (matcher.find()) {
                String refName = matcher.group().substring(1);
                String ref = packageFromName(refName);
                if (ref == null) {
                    ConsoleSender.err("&c错误的包地址引用 '" + matcher.group() + "', 于引用: " + key + " 中引用了错误的地址: " + refName + " (引用的地址不存在.)");
                    continue;
                }
                pkg = pkg.replace(matcher.group(), ref);
            }
            pkg = pkg.replace(placeholderKeyRef, key);

            packages.put(key, pkg);
        });

        ConsoleSender.info("从配置文件中载入了 {0} 个程序包引用.", packages.size());
        ConsoleSender.debug("所有已加载的程序包: {0}", packages.values());
    }
}
